from django.db import models

# Create your models here.
from core.models import CoreModel
from django.contrib.auth import get_user_model

UserModel = get_user_model()


class Book(CoreModel):
    name = models.CharField(
        max_length=150,
        verbose_name="书籍名称",
        help_text="书籍名称",
    )
    author = models.CharField(max_length=150, verbose_name="作者", help_text="作者")
    created_by = models.ForeignKey(
        UserModel, on_delete=models.CASCADE, related_name="user_books"
    )

    class Meta:
        unique_together = ("name", "author")
        db_table = "system_books"
        verbose_name = "书籍管理"
        verbose_name_plural = verbose_name
        ordering = ("id",)

    def __str__(self):
        return self.name
    
    

class Store(CoreModel):
    name = models.CharField(max_length=150, unique=True,verbose_name="仓库名称", help_text="仓库名称")
    bio = models.TextField()
    owner = models.ForeignKey(
        UserModel, on_delete=models.CASCADE, related_name="user_stores"
    )

    class Meta:
        db_table = "system_stores"
        verbose_name = "仓库管理"
        verbose_name_plural = verbose_name
        ordering = ("id",)
        
    def __str__(self):
        return self.name
    
    
class StoreBook(CoreModel):
    store = models.ForeignKey(
        Store, on_delete=models.CASCADE, related_name="store_books"
    )
    book = models.ForeignKey(
        "Book", on_delete=models.CASCADE, related_name="store_books"
    )
    borrowed_by = models.ForeignKey(
        UserModel,
        on_delete=models.CASCADE,
        related_name="books_borrowed",
        null=True,
        blank=True,
    )
    is_available = models.BooleanField(default=True)

    class Meta:
        db_table = "system_store_books"
        verbose_name = "仓库书籍"
        verbose_name_plural = verbose_name
        ordering = ("id",)
        unique_together = ("store", "book")

    def __str__(self):
        return f"{self.store.name[:10]}-{self.book.name[:5]}"

    def save(self, *args, **kwargs):
        self.is_available = False if self.borrowed_by else True
        return super().save(*args, **kwargs)
    
    
class StoreBookSubscription(CoreModel):
    store_book = models.ForeignKey(
        StoreBook, on_delete=models.CASCADE, related_name="subscribers"
    )
    subscriber = models.ForeignKey(
        UserModel, on_delete=models.CASCADE, related_name="waiting_store_book"
    )

    class Meta:
        db_table = "system_book_subscription"
        verbose_name = "书籍订阅"
        verbose_name_plural = verbose_name
        unique_together = ("store_book", "subscriber")

    def __str__(self):
        return f"{self.store_book.store.name[:10]}-{self.store_book.book.name[:5]}"
    
    

